<?php
namespace app\user2\model;

use think\Model;

class UserModel extends Model
{
    //检查昵称未被占用
    public function checkNicknameVacant($nickname)
    {
        $record=$this->where(["nickname"=>$nickname])->find();
        if($record){
            $this->error="昵称已被占用";
            return false;
        }
        return true;
    }
    public function checkLoginStatus()
    {
        $token=input("token");
        if(!$token){
            $this->error="token不能为空";
            return false;
        }
        session_id($token);
        $user=session("user");
        if(!$user){
            $this->error="用户未登录";
            return false;
        }
        return $user;
    }
    public function updateLoginStatus($user)
    {
        session("user",$user);
        $user["token"]=session_id();
        return $user;
    }
    //注册用户
    public function register($nickname,$password)
    {
        if(!$this->checkNicknameVacant($nickname)){
            return false;
        }
        $id=$this->create([
            "nickname"=>$nickname,
            "password"=>$password
        ])->id;
        if(!$id){
            $this->error="创建用户失败";
            return false;
        }
        $user=$this->where(["id"=>$id])->find()->getData();
        $user=$this->updateLoginStatus($user);
        return $user;
    }
    public function login($where,$password)
    {
        $user=$this->where($where)->find()->getData();
        if(!$user){
            $this->error="账号不存在";
            return false;
        }
        if($user["password"]!==$password){
            $this->error="密码错误";
            return false;
        }
        $user=$this->updateLoginStatus($user);
        return $user;
    }
}